package cn.itsource.pethome.org.service.impl;

import cn.itsource.pethome.basic.service.impl.BaseServiceImpl;
import cn.itsource.pethome.basic.util.MD5Utils;
import cn.itsource.pethome.basic.util.StrUtils;
import cn.itsource.pethome.org.domain.Employee;
import cn.itsource.pethome.org.mapper.EmployeeMapper;
import cn.itsource.pethome.org.service.IEmployeeService;
import cn.itsource.pethome.user.domain.LoginInfo;
import cn.itsource.pethome.user.mapper.LoginInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Override
    public void save(Employee employee) {
        //设置登录信息
        LoginInfo loginInfo = employee2LoginInfo(employee);
        //保存loginInfo
        loginInfoMapper.save(loginInfo);
        //给employee中的loginInfo赋值
        employee.setLoginInfo(loginInfo);
        //将employee的密码转化
        employee.setPassword(loginInfo.getPassword());
        //保存employee
        employeeMapper.save(employee);
    }

    /**
     * 设置登录信息
     * @param employee
     * @return
     */
    private LoginInfo employee2LoginInfo(Employee employee) {
        //创建LoginInfo对象
        LoginInfo loginInfo = new LoginInfo();
        //设置loginInfo属性值
        loginInfo.setUsername(employee.getUsername());
        loginInfo.setPhone(employee.getPhone());
        loginInfo.setEmail(employee.getEmail());
        loginInfo.setSalt(StrUtils.getComplexRandomString(10));
        loginInfo.setPassword(MD5Utils.encrypByMd5(employee.getPassword() + loginInfo.getSalt()));
        //标记后端用户
        loginInfo.setType(false);
        return loginInfo;
    }
}
